Imports FetchXMLBuilder.CrmServiceSdk

Public Class frmQuery

    Private CrmServiceURL As String
    Friend QueryFetchXML As String
    Private Type As QueryType


    Friend Sub New(ByVal CrmServiceURL As String, ByVal QueryType As QueryType)

        ' This call is required by the Windows Form Designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        Me.CrmServiceURL = CrmServiceURL
        Me.Type = QueryType
    End Sub

    Private Sub frmQuery_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Try
            Me.Cursor = Cursors.WaitCursor
            Dim query, result As String
            If Me.Type = QueryType.User Then
                Me.Name = "User Query"
                query = "<fetch mapping='logical'><entity name='userquery'><attribute name='name'/><attribute name='fetchxml'/></entity></fetch>"
            Else
                Me.Name = "Saved Query"
                query = "<fetch mapping='logical'><entity name='savedquery'><attribute name='name'/><attribute name='fetchxml'/></entity></fetch>"
            End If
            Dim service As New CrmService
            service.Credentials = Helpers.cred
            service.Url = Me.CrmServiceURL
            result = service.Fetch(query)
            Dim doc As New Xml.XmlDocument
            doc.LoadXml(result)
            Dim node As Xml.XmlNode
            Me.lstQueries.Items.Clear()
            For Each node In doc.DocumentElement.ChildNodes
                Me.lstQueries.Items.Add(New Query(node))
            Next
            Me.Cursor = Cursors.Default
        Catch soapexc As System.Web.Services.Protocols.SoapException
            Me.Cursor = Cursors.Default
            Me.QueryFetchXML = soapexc.Detail.InnerXml & vbCrLf
            If Not soapexc.InnerException Is Nothing Then
                Me.QueryFetchXML &= soapexc.InnerException.Message
            End If
        Catch exc As Exception
            Me.QueryFetchXML = exc.Message
            Me.Cursor = Cursors.Default
        End Try
    End Sub

    Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click
        Me.QueryFetchXML = CType(Me.lstQueries.SelectedItem, Query).node.ChildNodes(1).InnerText
        Me.DialogResult = Windows.Forms.DialogResult.OK
        Me.Close()
    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Me.DialogResult = Windows.Forms.DialogResult.Cancel
        Me.Close()
    End Sub

End Class

Friend Enum QueryType
    User
    Saved
End Enum

Friend Class Query
    Friend node As Xml.XmlNode
    Sub New(ByVal node As Xml.XmlNode)
        Me.node = node
    End Sub
    Overrides Function ToString() As String
        Return node.ChildNodes(0).InnerText
    End Function
End Class